import AWS from "aws-sdk";

class CloudStorage {
  constructor() {
    this.s3 = new AWS.S3({
      apiVersion: "2006-03-01",
      endpoint: "http://192.168.5.47:9000",
      accessKeyId: "admin",
      secretAccessKey: "zhixin@123",
      s3ForcePathStyle: true,
    });
    this.bucket = "test";
    this.dir = "mail";
    this.options = { partSize: 1000 * 1024 * 1024, queueSize: 1 };
  }

  // 单文件上传
  upload({ file, progressFn }) {
    console.log("file", file);
    const self = this;
    return new Promise((resolve, reject) => {
      let params = {
        Bucket: this.bucket,
        Key: `${self.dir}/${new Date().getTime()}/${file.name}`,
        Body: file,
      };
      let uploader = self.s3.upload(params, self.options);
      uploader.on("httpUploadProgress", (p) => {
        let progress = ((p.loaded / p.total) * 100).toFixed(0);
        progressFn(progress);
      });
      uploader.send((err, data) => {
        if (err) {
          console.log("文件上传云存储失败", err);
          reject(err);
        } else {
          console.log("文件上传云存储成功", data);
          resolve({ data, state: 1, file });
        }
      });
    });
  }

  // 批量上传文件
  uploadFiles({ files, totelProgressFn }) {
    const self = this;
    return new Promise(async (resolve, reject) => {
      let tempArr = Array.from(files);
      let resArr = [];
      for (let i = 0; i < tempArr.length; i++) {
        const file = tempArr[i];
        let progressFn = function (data) {
          let uploadInfo = {
            index: i,
            name: file.name,
            progress: data,
          };
          totelProgressFn(uploadInfo);
        };
        let res = await self.upload({ file, progressFn });
        resArr.push(res);
      }
      resolve({ data: resArr, state: 1 });
    });
  }

  // 下载文件
  downFile({ fileName, progressFn }) {
    const self = this;
    return new Promise((resolve, reject) => {
      let params = {
        Bucket: self.bucket,
        Key: fileName,
      };
      let downLoader = self.s3.getObject(params);
      downLoader.on("httpDownloadProgress", (p) => {
        let progress = ((p.loaded / p.total) * 100).toFixed(0);
        progressFn(+progress);
      });

      downLoader.send((err, data) => {
        if (err) {
          console.log("文件下载云存储失败", err);
          reject(err);
        } else {
          // 保存文件
          self.downLoadFile(data.Body, fileName);
          console.log("文件下载云存储成功", data);
          resolve({ data, state: 1 });
        }
      });
    });
  }

  //通过流下载文件
  downLoadFile(data, fileName) {
    const url = window.URL.createObjectURL(
      new Blob([data], {
        type: "application/octet-stream",
      })
    );
    const link = document.createElement("a");
    link.style.display = "none";
    link.href = url;
    link.setAttribute("download", fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  // 获取单文件访问地址
  getFileUrl(fileName) {
    const self = this;
    return new Promise((resolve, reject) => {
      let params = { Bucket: self.bucket, Key: fileName, Expires: 6000 };
      self.s3.getSignedUrlPromise("getObject", params, function (err, url) {
        console.log("The URL is", url);
        if (err) {
          reject(err);
        } else {
          resolve({ url, state: 1 });
        }
      });
    });
  }

  // 删除文件【支持批量】
  deleteFile(fileInfoArray) {
    console.log("fileInfoArray", fileInfoArray);
    const self = this;
    return new Promise((resolve, reject) => {
      var params = {
        Bucket: self.bucket,
        Delete: {
          Objects: fileInfoArray,
          Quiet: false,
        },
      };
      console.log("params", params);
      self.s3.deleteObjects(params, function (err, data) {
        if (err) {
          reject(err);
        } else {
          resolve({ data, state: 1 });
        }
      });
    });
  }

  // 获取存储桶里面的文件列表
  getFileListInBucket(parm = {}) {
    const self = this;
    return new Promise((resolve, reject) => {
      let params = { Bucket: self.bucket, ...parm };
      self.s3.listObjects(params, function (err, data) {
        if (err) {
          reject(err);
        } else {
          resolve({ data, state: 1 });
        }
      });
    });
  }
}

// 返回单例
function getS3Instance() {
  if (!CloudStorage.instance) {
    CloudStorage.instance = new CloudStorage();
  }
  return CloudStorage.instance;
}

export default getS3Instance;
